﻿// 版权所有：
// 文 件  名：ConfigHelper.cs
// 功能描述：配置文件操作类 2013-1-5 马山林 添加
// 创建标识：Seven Song(m.sh.lin0328@163.com) 2014/1/18 16:55:57
//----------------------------------------------------------------*/
using System;
using System.Text;
using System.Xml;

namespace MslDiary.Framework.IO
{
    public class ConfigHelper
    {
        #region 变量
        private XmlDocument xmlDoc;
        private string xmlfilepath = string.Empty;
        public const string ROOT_NODE = "Configuration";
        /// <summary>
        /// XML的根节点
        /// </summary>
        private XmlElement root;
        #endregion

        /// <summary>
        /// 构造函数，导入Xml文件
        /// </summary>
        /// <param name="xmlFile">文件路径或xml文件文本</param>
        public ConfigHelper(string xmlFile)
        {
            xmlDoc = new XmlDocument();
            xmlfilepath = xmlFile;
            xmlDoc.Load(xmlFile);   //载入Xml文档
            //为XML的根节点赋值
            root = xmlDoc.DocumentElement;
        }
        ~ConfigHelper()
        {
            if (xmlDoc != null)
                xmlDoc = null;  //释放XmlDocument对象
        }
        public void Save()
        {
            xmlDoc.Save(xmlfilepath);
        }
        public XmlNode GetNodeByKey(string strNode)
        {
            return xmlDoc.SelectSingleNode(strNode);
        }
        /// <summary>
        /// 节点查询，返回节点值
        /// </summary>
        /// <param name="nodePath">节点的路径 如:Data/ArticleInfo/ArticleTitle</param>
        /// <returns></returns>
        public string SelectNodeTextByPath(string nodePath)
        {
            string _nodeTxt = xmlDoc.SelectSingleNode(nodePath).InnerText;
            if (_nodeTxt == null || _nodeTxt == "")
                return "";
            else
                return _nodeTxt;
        }
        /// <summary>
        /// 设置节点值
        /// </summary>
        /// <param name="xPath">节点名</param>
        /// <param name="xmlNodeValue">节点值</param>
        public void SetNodeValueByPath(string xPath, string xmlNodeValue)
        {
            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xPath);
                xmlNode.InnerText = xmlNodeValue;
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
        }
        /// <summary>
        /// 从 xPath 中移除子节点 childPath
        /// </summary>
        /// <param name="xPath"></param>
        /// <param name="childPath"></param>
        public void RemoveNodeValueByPath(string xPath, string childPath)
        {
            try
            {
                XmlNode xmlNode = xmlDoc.SelectSingleNode(xPath);
                XmlNode childNode = xmlDoc.SelectSingleNode(childPath);
                if (childNode != null)
                    xmlNode.RemoveChild(childNode);
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
        }
        public XmlNodeList SelectSelectNodes(string xPath)
        {
            try
            {
                return xmlDoc.SelectNodes(xPath);
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
        }
        public string GetValueByKey(string node)
        {
            string obj = SelectNodeTextByPath(ROOT_NODE + "/" + node);
            if (obj == null)
                obj = String.Empty;

            return obj.Trim();
        }
        /// <summary>
        /// 设置节点属性值 
        /// </summary>        
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        /// <param name="attributeName">属性名 可以为空</param>
        /// <param name="attributeValue">属性值</param>
        public void SetAttribute(string xPath, string attributeName, string attributeValue)
        {
            try
            {
                //根据指定路径获取节点
                XmlNode xmlNode = root.SelectSingleNode(xPath);
                xmlNode.Attributes[attributeName].Value = attributeValue;
            }
            catch (XmlException xmle)
            {
                throw xmle;
            }
        }
        /// <summary>
        /// 节点是否存在 
        /// </summary>        
        /// <param name="xPath">XPath表达式,
        /// 范例1: @"Skill/First/SkillItem", 等效于 @"//Skill/First/SkillItem"
        /// 范例2: @"Table[USERNAME='a']" , []表示筛选,USERNAME是Table下的一个子节点.
        /// 范例3: @"ApplyPost/Item[@itemName='岗位编号']",@itemName是Item节点的属性.
        public bool NodeIsExists(string xPath)
        {
            try
            {
                //根据指定路径获取节点
                XmlNode xmlNode = root.SelectSingleNode(xPath);
                return xmlNode != null;
            }
            catch (XmlException e)
            {
                MSL.Tool.LogHelper.Instance.WriteLog(e.ToString());
                return false;
            }
        }
        /// <summary>
        /// 添加属性
        /// </summary>
        /// <param name="xPath">属性所在节点</param>
        /// <param name="attribute">属性名</param>
        /// <param name="attributeValue">属性值</param>
        /// <returns></returns>
        public bool AddAttribute(string xPath, string attribute, string attributeValue)
        {
            try
            {
                XmlElement xe = (XmlElement)root.SelectSingleNode(xPath); //强制转化成XmlElement对象
                xe.SetAttribute(attribute, attributeValue);    //XmlElement对象添加属性方法     
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <param name="xPath">节点</param>
        /// <param name="element">元素名，非空时插入新元素，否则在该元素中插入属性</param>
        /// <param name="attribute">属性名，非空时插入该元素属性值，否则插入元素值</param>
        /// <param name="value">值</param>
        /// <returns></returns>
        /**************************************************
         * 使用示列:
         * XmlHelper.AppendNode(path, "/Node", "Element", "", "Value")
         * XmlHelper.AppendNode(path, "/Node", "Element", "Attribute", "Value")
         * XmlHelper.AppendNode(path, "/Node", "", "Attribute", "Value")
         ************************************************/
        public void AppendNode(string xPath, string element, string attribute, string value)
        {
            try
            {
                XmlNode xn = root.SelectSingleNode(xPath);
                if (element.Equals(""))
                {
                    if (!attribute.Equals(""))
                    {
                        XmlElement xe = (XmlElement)xn;
                        xe.SetAttribute(attribute, value);
                    }
                }
                else
                {
                    XmlElement xe = xmlDoc.CreateElement(element);
                    if (attribute.Equals(""))
                        xe.InnerText = value;
                    else
                        xe.SetAttribute(attribute, value);
                    xn.AppendChild(xe);
                }
                Save();
            }
            catch { }
        }
        public void SetValueByKey(string node, string nodeVal)
        {
            SetNodeValueByPath(ROOT_NODE + "/" + node, nodeVal);
        }
    }
}
